import * as turf from '@turf/turf';
import { setMarker, addMarker } from '@/utils/initMap';

export const vehicleInsList = {};
class Vehicle {
  positionList = []; // 坐标列表
  length = 0; // 当前坐标列表长度
  hasLine = false; // 当前是否在执行轨迹段
  timeLine = 0; // 记录当前轨迹段执行时长
  prevTime = null; // 记录轨迹中上一个时间节点
  prevPosTimestamp = new Date().valueOf();
  timeInterval = [];
  isReStart = false;
  curTrackSegment = {
    dis: 0,
    bearing: 0,
  }; // 当前轨迹段长度
  constructor(data) {
    this.push(data);
    addMarker(data.coordinates, data.speedangle);
  }
  push(data) {
    this.vehicleData = data;
    if (this.length > 4) {
      this.shift();
    }
    this.positionList.push(data.coordinates);
    this.length++;
    if (this.length >= 2) {
      this.timeInterval.push(new Date().valueOf() - this.prevPosTimestamp);
      !this.hasLine && this.startMove();
    }
  }
  shift() {
    if (this.length <= 0) {
      return;
    }
    this.positionList.shift();
    this.length--;
    if (this.length < 2) {
      this.hasLine = false;
    }
  }
  startMove() {
    this.hasLine = true;
    if (this.isReStart) {
      this.setMove(this.dealPosition());
      return;
    }
    this.prevTime = new Date().valueOf();
    this.dealTrackSegment();
    window.requestAnimationFrame(() => {
      this.setMove(this.positionList[0]);
    });
  }
  setMove(coordinates) {
    setMarker(coordinates, this.vehicleData.speedangle);
    const curTime = new Date().valueOf();
    const duration = curTime - this.prevTime;
    this.prevTime = curTime;
    this.timeLine += duration;

    if (this.timeLine >= this.timeInterval[0]) {
      this.timeLine = this.timeLine - this.timeInterval[0];
      this.shift();
      this.dealTrackSegment();
    }
    if (this.hasLine) {
      requestAnimationFrame(() => {
        this.setMove(this.dealPosition());
      });
    }
  }
  pauseMove() {
    this.hasLine = false;
    this.isReStart = true;
  }
  // 轨迹段处理
  dealTrackSegment() {
    if (!this.hasLine) return;
    const from = turf.point(this.positionList[0]);
    const to = turf.point(this.positionList[1]);
    const options = { units: 'miles' };
    this.curTrackSegment.dis = turf.distance(from, to, options);
    this.curTrackSegment.bearing = turf.rhumbBearing(from, to);
  }
  // 获取下一个移动节点
  dealPosition() {
    const from = turf.point(this.positionList[0]);
    const { dis, bearing } = this.curTrackSegment;
    const options = { units: 'miles' };
    return (
      turf.destination(
        from,
        (dis * this.timeLine) / this.timeInterval[0],
        this.vehicleData.speedangle,
        // bearing,
        options
      )?.geometry?.coordinates || this.positionList[0]
    );
  }
}

export default Vehicle;
